import {
  getPage,
  getImage
} from '../../utils/config';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
import {
  promisify,
  http,
  $toast,
  $query
} from '../../utils/utils';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPage: getPage,
    getImage: getImage,
    loading: 0,
    logged: 0,
    userId: '',
    loadmore: false,
    loaddone: false,
    abnor: false,
    imgheights: {},
    curBannerHeight: 0,
    showtips: 0,
    productcases1: [],
    xqList: [],
    vdList: [],
    sharehow:false,
    shareid:'',
    share_id:'',
    proList:[],
    anlipage:1,
    anlipages:0,
  },

  // 去产品详情
  goproductdetail(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    if (data.id) {
      wxApi.navigateTo(getPage.productdetail, {
        id: data.id
      });
    }
  },

  goChaXunPrice(){
    let {info,ShopInfo} = this.data;
    wxApi.navigateTo(getPage.mfshejiprice,{
      type: 1,
      id:info.id,
      picurl:info.picurl,
      price:info.price,
      discount_price:info.discount_price,
      title:info.productname,
      receiver: ShopInfo.UserId,

      gochat_id: ShopInfo.ShopId,
      gochat_user_name: ShopInfo.ShopName,
      gochat_img: ShopInfo.picurl,
      gochat_touserid: ShopInfo.UserId
    });
  },

  // 点击头像跳转店铺首页
  gocompanydetail() {
    const data = this.data.ShopInfo;
    if (data.ShopId) {
      wxApi.navigateTo('/pages/companydetail/index', {
        id: data.ShopId
      });
    }
  },
  
  imageLoad: function (e) { //获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  /**
   * 返回上一页
   */
  goBackTap() {
    //存在上一页,关闭当前返回一层,//没有上一页，跳回首页
    this.data.getPages > 1 ? wxApi.navigateBack(1) : wxApi.switchTab(getPage.home);
  },
  gohome() {
    wx.switchTab({
      url: getPage.home,
    })
  },
  updateDot(data) {
    let dots = data.detail.dots;
    this.setData({
      dots
    })
  },
  callphone() {
    let {
      logged,
      shopInfo,
      showtips,
      contacters
    } = this.data;
    let _this = this;
    var itemList = [];
    contacters.forEach(element => {
      itemList.push(element.contacter + " " + element.tel);
    });
    if (logged) {
      if (showtips == 0) {
        wx.showModal({
          title: '防骗提醒',
          content: '陌生电话要警惕，要求转账不要理',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              _this.setData({
                showtips: 1
              });
              wx.showActionSheet({
                itemList: itemList,
                success(res) {
                  console.log(res.tapIndex);
                  wx.makePhoneCall({
                    phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
                    success: function () {
                      console.log("拨打电话成功！")
                    },
                    fail: function () {
                      console.log("拨打电话失败！")
                    }
                  })
                },
                fail(res) {
                  console.log(res.errMsg)
                }
              })
            }
          }
        })
      } else {
        wx.showActionSheet({
          itemList: itemList,
          success(res) {
            console.log(res.tapIndex);
            wx.makePhoneCall({
              phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
              success: function () {
                console.log("拨打电话成功！")
              },
              fail: function () {
                console.log("拨打电话失败！")
              }
            })
          },
          fail(res) {
            console.log(res.errMsg)
          }
        })

        console.log(this.data.contacters)
      }
    } else {
      this.jumpLogin();
    }
  },

  /**
   * 关注店铺
   */
  followClick() {
    var {
      logged,
      userId,
      id,
      is_fav,
      fans
    } = this.data;
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'fav_shopproduct',
          userid: userId,
          id: id,
        }
      }).then((res) => {
        let {errmsg,data} = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        // fans = fans + 1;
        is_fav = data;
        this.setData({
          // fans: fans,
          is_fav: is_fav
        });
      })
    } else {
      this.jumpLogin();
    }
  },

  gotousu() {
    let {
      logged,
      info,
      ShopInfo
    } = this.data;
    if (logged) {
      wxApi.navigateTo(getPage.tousu + "?id=" + ShopInfo.ShopId + "&name=" + ShopInfo.ShopName + "&type=产品" + "&title=" + info.productname);
    } else {
      this.jumpLogin();
    }
  },

  gosekadetail(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    let {
      id
    } = this.data;
    wxApi.navigateTo(getPage.sekadetail, {
      id,
      seka_id: data.id
    });
  },

  // 去案例详情
  goanlidetail(e) {
    console.log('eeeeeeeeeeee', e)
    const data = e.currentTarget.dataset || e.target.dataset;
    let {
      ShopInfo
    } = this.data;
    if (data.id) {
      wxApi.navigateTo(getPage.anlidetail, {
        id: data.id,
        picurl: ShopInfo.picurl,
        ShopName: ShopInfo.ShopName,
        ShopId: ShopInfo.ShopId,
        UserId: ShopInfo.UserId,
        ShopType: ShopInfo.ShopType
      });
    }
  },

  /**
   * 跳转登录页
   */
  jumpLogin() {
    wxApi.setStartPage({
      id: this.data.shopid
    });
    wxApi.navigateTo(getPage.login);
  },


  /**
   * 监听页面--滚动
   */
  scrollChange(e) {

  },
  onPreviewImage(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    var showmenu = true;
    const {
      swiper
    } = this.data;
    console.log(data.id);
    const item = swiper[data.id];
    wx.previewImage({
      urls: swiper.map((item) => api.imageCdn + item.picurl),
      current: api.imageCdn + item.picurl,
      showmenu,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },
  showDetailImg(e) {
    console.log(e)
    let cur_url = e.currentTarget.dataset.cur+ '?x-oss-process=image/resize,w_1000/quality,q_100/watermark,image_c2h1aXlpbi5wbmc=';
    let urls = this.data.xqList.map(m => {
      return m + '?x-oss-process=image/resize,w_1000/quality,q_100/watermark,image_c2h1aXlpbi5wbmc='
    })
    wx.previewImage({
      urls: urls,
      current: cur_url,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },
  gochat() {
    var {
      logged,
      ShopInfo,
      userId,
      info
    } = this.data;
    console.log(logged);
    if (logged) {
      let sendcard = info;
      sendcard.productid = info.id;
      let star_cont = JSON.stringify(info);
      http.post(api.default, {
        data: {
          action: 'sendmessage',
          sender: userId,
          receiver: ShopInfo.UserId,
          MessageType: 10,
          content: star_cont,
        }
      }).then((res) => {})
      wxApi.navigateTo(getPage.chat, {
        id: ShopInfo.ShopId,
        user_name: ShopInfo.ShopName,
        img: ShopInfo.picurl,
        touserid: ShopInfo.UserId
      });

    } else {
      this.jumpLogin();
    }

  },
  mediaload(e) {
    console.log('mediaload---------', e)
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  shareClose(){
    this.setData({
      sharehow:false
    })
  },
  goShare(){
    let { logged } = this.data;
    if(logged){
      http.post(api.default, {
        data: {
          action: 'addshopproductshare',
          userid: this.data.userId,
          shopid: this.data.ShopInfo.ShopId,
          productid:this.data.id
        }
      }, false).then(res=>{
        let {data} = res.data;
        this.setData({
          sharehow:true,
          share_id:data.id
        })
      })
    }else {
      this.jumpLogin();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    console.log('options', options)

    /**
     * 店铺id
     */
    if (JSON.stringify(options) !== '{}') {
      this.setData({
        id: options.id,
        shareid: options.shareid||'',
        // ShopInfo: {
        //   picurl: options.picurl,
        //   ShopName: options.ShopName,
        //   ShopId: options.ShopId,
        //   UserId: options.UserId,
        //   ShopType: options.ShopType
        // }, 
      });
    }
    //获取路由数量
    this.setData({
      getPages: getCurrentPages().length
    })
    /**
     * 获取system信息
     */
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
      console.log(this.data.window);
    });

    /**
     * 获取用户信息 
     */
    let logged, userId = '';
    app.getLogin().then((res) => {
      logged = res.code;
      userId = res.data.user.user_id;
    }).catch((res) => {
      logged = res;
    }).finally(() => {
      this.setData({
        logged,
        userId
      });
      /**
       * 获取店铺信息
       */
      let {
        id,
        pageSize,
        loaddone,
        abnor,
        shareid
      } = this.data;

      //第一部分数据加载
      http.post(api.default, {
        data: {
          action: 'getproductinfo',
          id: id,
          userid: userId,
          shareid: shareid,
        }
      }, false).then((res) => {
        const {
          data
        } = res.data;
        console.log(data);
        let swiper = []
        data.videolist?.forEach(item => {
          item.type = 1;
          swiper.push(item)
        })
        data.filelist.forEach(item => {
          item.type = 0;
          swiper.push(item)
        })
        let xqArr = data.xqlist.map(m => m.url)
        let vdArr = data.videolist.map(m => m.url)

        let sekaList = data.info.seka ? JSON.parse(data.info.seka) : []

        this.setData({
          info: data.info,
          swiper: swiper,
          xqList: xqArr,
          vdList: vdArr,
          ShopInfo: data.ShopInfo,
          is_fav: data.is_fav,
          sekaList,
        });
        //请求数据
        this.handleGetAnliList((res) => {
          this.setData({
            proList: res.list
          });
        })
      });

      // 获取相关案例
      this.getproductcases()

    });

    /**
     * scrollTop
     */
    this.scrollTop = 0;
    this.scrollHeight = 0;

    /**
     * 获取收缩对象高度
     */
    $query.select('#headInfo', (data) => {
      this.headInfo = data;
    });
  },

  // 获取相关案例
  getproductcases() {
    let params = {
      action: 'getproductcases',
      productid: this.data.id
    }
    http.post(api.default, {
      data: params
    }, false).then(res => {
      console.log('res++++++++++', res.data.data)
      this.setData({
        productcases: res.data.data
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  handleGetAnliList(cb, a = false){
    let { 
      anlipage,
      anlipages,
      loaddone,
      abnor,
      info
     } = this.data;
     console.log('sssssssssssssss',info)
    http.post(api.default, {
      data: {
        action: 'getshopproducts',
        shopid: 0,
        plat_cid: info.plat_categoryid,
        pageindex: anlipage
      }
    }, a).then(res=>{
      const {
        data
      } = res.data;
      console.log('data-------',data)

      //是否加载完毕

      if (data.pages == 0)
        abnor = true;
      else
        abnor = false;
      if (anlipage == data.pages && !abnor) loaddone = true;
      this.setData({
        anlipages: data.pages,
        loaddone,
        abnor
      });
      cb && cb(data);
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('到底了')
    let {
      anlipage,
      anlipages,
      loadmore
    } = this.data;
    console.log('anlipages',anlipages,anlipage)

    if (anlipages >= anlipage && !loadmore) {
      anlipage++;
      loadmore = false;

      //显示加载效果
      this.setData({
        anlipage,
        loadmore
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.handleGetAnliList((res) => {
        console.log('底部---------getProductsInfo')
        let {
          proList
        } = this.data;
        loadmore = false;
        this.setData({
          loadmore,
          proList: proList.concat(res.list)
        });
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
    var pageshare = getPage.productdetail + "?id=" + this.data.id + "&shareid=" + this.data.share_id;
    console.log('pageshare', pageshare);
    var picurl = "";
    if (this.data.swiper.length > 0){
      picurl = api.imageCdn + this.data.swiper[0].picurl;
    }
    this.setData({
      sharehow:false
    })
    return {
      title: `【可居】${this.data.info.productname}`,
      imageUrl: picurl,
      path: pageshare
    }
  }
})